<?php

class Module_gallery implements Module {
	private $albumDefault = '/images/camera.gif';
	private $maxSideSize = 700;
	private $thumbSize = 200;

	public function run() {
		if (isset($_GET['album']) && $_GET['album'] == 'new') {
			$this->createAlbum();
		} elseif (isset($_GET['photo']) && $_GET['photo'] == 'upload') {
			$this->upload((int)$_GET['album_id']);
		} elseif (isset($_GET['photo']) && $_GET['photo'] == 'edit') {
			$this->edit((int)$_GET['album_id']);
		} elseif (isset($_GET['album']) && is_numeric($_GET['album'])) {
			$this->showAlbums((int)$_GET['album']);
		} elseif (isset($_GET['album']) && $_GET['album'] == 'delete') {
			$this->deleteAlbum((int)$_GET['album_id']);
		} elseif (isset($_GET['album']) && $_GET['album'] == 'edit') {
			$this->editAlbum((int)$_GET['album_id']);
		} else {
			$this->showAlbums();
		}
	}

	private function showAlbums($album = 0){
		if ($album) {// show photos
			$file = '';
			$albums = Mysql::getInstance()->select('photos','*','parent=' . (int)$album);
			$href = 'photo';
			$template = 'gallery_item_photo';
			$templateMain = 'gallery_photos';

			if(Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('uid'),'gallery_manage_photos') ){
				$actions[] = '<a href="'.Url::formatUrl('gallery',array('photo'	=>	'upload','album_id'	=> (int)$album)).'">'.__('Додати фото').'</a>';
				$actions[] = '<a href="'.Url::formatUrl('gallery',array('photo'	=>	'edit','album_id'	=> (int)$album)).'">'.__('Редагувати фото').'</a>';
				$actions[] = '<a onclick="if(confirm(\''.__('Видалити альбом?').'\'){return false;} else {return false;})" href="'.Url::formatUrl('gallery',array('album'	=>	'delete','album_id'	=> (int)$album)).'">'.__('Видалити альбом').'</a>';
				$actions[] = '<a href="'.Url::formatUrl('gallery',array('album'	=>	'edit','album_id'	=> (int)$album)).'">'.__('Редагувати альбом').'</a>';
				$actions = implode(' | ',$actions);
			} else {
				$actions = '';
			}

			$imI = 'image';
			$imEnd = '.jpg';
			$imEndThumb = '_thumb';
		} else {//show albums
			$file = '/templates/'.Config::get('template');
			$albums = Mysql::getInstance()->select('photoalbums');
			$href = 'album';
			$template = 'gallery_item_album';
			$templateMain = 'gallery_albums';

			if(Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('uid') ,'gallery_manage_albums') ){
				$actions[] = '<a href="'.Url::formatUrl('gallery',array('album'	=>	'new')).'">'.__('Додати альбом').'</a>' ;
				$actions = implode(' | ',$actions);
			} else {
				$actions = '';
			}

			$imI = 'thumb';
			$imEnd = '';
			$imEndThumb = '';
		}

		$items = '';
		foreach ($albums as $item) {
			if ($album) {//	show photos
				$file = '/uploads/gallery/' . $album . '/' . $item['image'];
			} else {//		show albums
				$file = ($item['thumb'] !== '' && is_file( ROOT. '/uploads/gallery/' . $item['id']. '/' .$item['thumb'].'_thumb.jpg')) ? '/uploads/gallery/' . $item['id']. '/' .$item['thumb'].'_thumb.jpg' :$file . $this->albumDefault ;
			}


			$tpl = Template::getInstance();
			$tpl->load($template);
			$tpl->set('{file}',$file .$imEnd);
			$tpl->set('{file_thumb}',$file  . $imEndThumb .$imEnd);
			$tpl->set('{href}',Url::formatUrl('gallery',array($href => $item['id'])));
			$tpl->set('{description}', isset($item['description']) ? nl2br(htmlspecialchars(stripslashes($item['description']))) : '');

			if (!$album) {//	show photos
				$tpl->set('{album-name}',stripslashes($item['name']));
			}
			$items .= $tpl->out();
		}

		$tpl = Template::getInstance();
		$tpl->load( $templateMain );
		$tpl->set('{gallery}',$items);
		$tpl->set('{actions}',$actions);
		if ($album) {
			$desc = Mysql::getInstance()->select('photoalbums','description','id='.$album);
			$tpl->set('{description}',$desc[0]['description']);
		}

		Aurus::getInstance()->addContent( $tpl->out() );
	}

	private function deleteAlbum($albumId){
		Mysql::getInstance()->delete('photoalbums','id='.$albumId);
		$this->deleteDirectory( ROOT. '/uploads/gallery/' . $albumId . '/');
	}

	private function editAlbum($album){
		$album = (int)$album;
			if (isset($_POST['name'])) {
				if (!trim($_POST['name'])) {
					Aurus::getInstance()->setError(__('Вкажіть ім\'я для альбому'));
				} else {
					
					Mysql::getInstance()->update('photoalbums',
					array(
					'name' => Mysql::getInstance()->escape($_POST['name']),
					'description' => Mysql::getInstance()->escape($_POST['description']),
					),'id='.$album);

					Aurus::getInstance()->setInfo(__('Альбом оновлено'));
				}
			} else {
				$info = Mysql::getInstance()->select('photoalbums','*','id='.$album);
				$info = $info[0];
				
				
				$tpl = Template::getInstance();
				$tpl->load('new_album');
				$tpl->set('{name}',$info['name']);
				$tpl->set('{description}',$info['description']);
				Aurus::getInstance()->addContent( Aurus::getInstance()->form_start() .$tpl->out(). '</form>' );
			}

	}

	private function deleteDirectory($dirname) {
		if (is_dir($dirname)) {
			$dir_handle = opendir($dirname);
		}
		if (!$dir_handle){
			return false;
		}
		while($file = readdir($dir_handle)) {
			if ($file != "." && $file != "..") {
				if (!is_dir($dirname."/".$file)) {
					unlink($dirname."/".$file);
				} else {
					$this->deleteDirectory($dirname.'/'.$file);
				}
			}
		}
		closedir($dir_handle);
		rmdir($dirname);
		return true;
	}

	private function edit($album){
		$photos = Mysql::getInstance()->select('photos','*','parent=' . (int)$album);

		$items = '';
		foreach ($photos as $item) {
			$tpl = Template::getInstance();
			$tpl->load('gallery_item_photo_edit');

			$tpl->set('{id}',$item['id']);
			$tpl->set('{photo}','/uploads/gallery/'.$album.'/'.$item['image'].'_thumb.jpg');
			$tpl->set('{description}',$item['description']);
			$tpl->set('{album}',$item['parent']);

			$items .= $tpl->out();
		}


		$tpl = Template::getInstance();
		$tpl->load( 'gallery_photos' );
		$tpl->set('{gallery}',$items);
		$tpl->set('{actions}');
		$tpl->set('{description}');
		Aurus::getInstance()->addContent( $tpl->out() );
	}

	private function upload($uploadTo){
		if (isset($_FILES['photo'])) {
			if (Users::getInstance()->isValidName($_GET['user'] )) {

				$result = Mysql::getInstance()->select('users','*','login="'.$_GET['user'] .'" AND password="'.$_GET['pass'].'"');
				$user = $result[0];

				if (is_array($user) && Users::getInstance()->can($user['group'], 'gallery_manage_photos') ){
					$this->uploadFile($_FILES['photo'], (int)$user['uid'], (int)$_GET['album_id']);
				}

				exit(format(__('Файл {%1%} завантажено'),$_FILES['photo']['name']));
			} else {
				exit(format(__('Файл {%1%} не завантажено'),$_FILES['photo']['name']));
			}
		} else {
			$tpl = Template::getInstance();
			$tpl->load( 'gallery_upload' );
			$tpl->set('{album_id}',$uploadTo);
			$tpl->set('{user}',Users::getInstance()->getLoggedUsersData('login'));
			$tpl->set('{pass}',Users::getInstance()->getLoggedUsersData('password'));
			Aurus::getInstance()->addContent( $tpl->out() );
		}
	}

	private function uploadFile($file, $user, $album){
		/* $_FILES[photo]
		[name] => DSCN0955.jpg
		[type] => application/octet-stream
		[tmp_name] => Z:\tmp\php563F.tmp
		[error] => 0
		[size] => 5126546
		*/

		$info = getimagesize($file['tmp_name']);
		$mime = $info['mime'];

		if($mime == 'image/jpeg'){
			$md5 = md5_file($file['tmp_name']);

			$this->saveResized($file['tmp_name'], ROOT . '/uploads/gallery/' . $album , $info, $md5);

			Mysql::getInstance()->insert('photos', array(
			'parent'	=>	$album,
			'author'=>	$user['uid'],
			'description'=>	'',
			'rating'=>	'0',
			'image'=>	$md5,
			));
		}
	}

	private function saveResized($imgPath, $savePath, $info, $md5){
		/* getimagesize()
		[0] => 2736
		[1] => 3648
		[2] => 2
		[3] => width="2736" height="3648"
		[bits] => 8
		[channels] => 3
		[mime] => image/jpeg
		*/

		$width = $info[0];
		$height = $info[1];
		if ($width > $height) {
			$ratio = $width/$this->maxSideSize;
		} else {
			$ratio = $height/$this->maxSideSize;
		}

		$newWidth = round($width/$ratio);
		$newHeight = round($height/$ratio);

		$res = imagecreatefromjpeg($imgPath);
		$newImage = imagecreatetruecolor($newWidth,$newHeight);

		imagecopyresized($newImage, $res, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

		imagejpeg($newImage, $savePath . '/'. $md5 . '.jpg', 100);

		$thumb = imagecreatetruecolor($this->thumbSize,$this->thumbSize);

		if ($width > $height) {
			imagecopyresized($thumb, $res, 0, 0, round((max($width,$height)-min($width,$height))/2), 0, $this->thumbSize, $this->thumbSize, min($width,$height), min($width,$height));
		} elseif ($width < $height) {
			imagecopyresized($thumb, $res, 0, 0, 0, 0, $this->thumbSize, $this->thumbSize, min($width,$height), min($width,$height));
		} else {
			imagecopyresized($thumb, $res, 0, 0, 0, 0, $this->thumbSize, $this->thumbSize, $height, $height);
		}

		imagejpeg($thumb, $savePath . '/'. $md5 . '_thumb.jpg', 100);
		imagedestroy($res);
		imagedestroy($newImage);
		imagedestroy($thumb);
	}

	private function createAlbum(){
		if (is_writable(ROOT . '/uploads/gallery')) {
			if (isset($_POST['name'])) {
				if (!trim($_POST['name'])) {
					Aurus::getInstance()->setError(__('Вкажіть ім\'я для альбому'));
				} else {
					Mysql::getInstance()->insert('photoalbums',
					array(
					'name' => Mysql::getInstance()->escape($_POST['name']),
					'description' => Mysql::getInstance()->escape($_POST['description']),
					));

					$lastId = mysql_insert_id();
					mkdir(ROOT . '/uploads/gallery/' . $lastId . '/');

					try {
						chmod(ROOT . '/uploads/gallery/' . $lastId . '/',0777);
					} catch (Exception $e) {
						Aurus::getInstance()->setError(__('Немає прав на зміну прав UNIX ('.$e.')'));
					}

					Aurus::getInstance()->setInfo(__('Альбом додано'));
				}
			} else {
				$tpl = Template::getInstance();
				$tpl->load('new_album');
				$tpl->set('');
				Aurus::getInstance()->addContent( Aurus::getInstance()->form_start() .$tpl->out(). '</form>' );
			}
		} else {
			Aurus::getInstance()->setError(__('Немає прав на запис в папку /uploads/gallery/'));
		}
	}

	public function onActivate() {
	$sql[] = "CREATE TABLE `" . PREFIX. "_photoalbums` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) NOT NULL,
 `description` text NOT NULL,
 `thumb` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";

	$sql[] = "CREATE TABLE `" . PREFIX. "_photos` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `parent` int(11) NOT NULL,
 `author` int(11) NOT NULL,
 `description` text NOT NULL,
 `rating` int(11) NOT NULL,
 `image` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
		foreach ($sql as $s) {
			Mysql::getInstance()->query($s);
		}
	}

	public function onDeactivate() {

	}

	public function initAdminArea() {

	}

	public function runAjax() {
		if (!Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('uid'),'gallery_manage_photos')){
			die('access denied');
		}

		if (isset($_POST['delete'])) {
			$this->deletePhoto((int) $_POST['delete']);
		} elseif (isset($_POST['set_as_logo'])){
			$photo = Mysql::getInstance()->select('photos','*','id='.(int) $_POST['set_as_logo']);
			$photo = $photo[0];

			Mysql::getInstance()->update('photoalbums', array('thumb' => $photo['image']),'id=' . (int)$_POST['album']);

			echo __('Фото було встановлене як обкладинка');
		} elseif(isset( $_POST['set_description'])) {
			if (!isset($_POST['desc'])){
				$_POST['desc'] = '';
			}
			Mysql::getInstance()->update('photos', array('description' => addslashes($_POST['desc'])), 'id=' . (int)$_POST['set_description']);

			echo __('Опис оновлений');
		}


	}

	private function deletePhoto($id){
		$photo = Mysql::getInstance()->select('photos','*','id='.$id);
		$photo = $photo[0];

		if (!is_file(ROOT . '/uploads/gallery/' . $photo['parent'] .'/' . $photo['image'] . '.jpg' )){
			touch(ROOT . '/uploads/gallery/' . $photo['parent'] .'/' . $photo['image'] . '.jpg' );
		}
		if (!is_file(ROOT . '/uploads/gallery/' . $photo['parent'] .'/' . $photo['image'] . '_thumb.jpg' )){
			touch(ROOT . '/uploads/gallery/' . $photo['parent'] .'/' . $photo['image'] . '_thumb.jpg' );
		}
		if (unlink(ROOT . '/uploads/gallery/' . $photo['parent'] .'/' . $photo['image'] . '.jpg' ) && unlink(ROOT . '/uploads/gallery/' . $photo['parent'] .'/' . $photo['image'] . '_thumb.jpg' )) {
			Mysql::getInstance()->delete('photos','id='.$id);
			echo '1';
		} else {
			echo 'Can not remove files';
		}
	}
}